package com.jt.service;

import com.jt.pojo.User;
import com.jt.util.ObjectMapperUtil;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
/**HttpClient:在java中发起请求的API
 * <hr>1.实例化HttpClient客户端的对象
 * <br>2.定义url的地址
 * <br>3.定义请求类型
 * <br>4.发起HttpClient请求
 * <br>5.获取相应的结果,分析状态码信息 200 404 502.....
 * <br>6.获取结果进行后续的操作
 */
@Service
public class HttpClientServiceImpl implements HttpClientService {
    @Override
    public List<User> findUserList() {
        List<User> userList = new ArrayList<>();
        //web需要向sso获取数据
        HttpClient httpClient = HttpClients.createDefault();
        String url = "http://sso.jt.com/user/findUserList";//浏览器发起的请求违反了同源策略才叫跨域,这个是java发起的,所以不叫跨域
        //此时有两次请求,第一次是浏览器发起的请求,第二次是HttpClient发起的请求
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse httpResponse = httpClient.execute(httpGet);
            if (httpResponse.getStatusLine().getStatusCode()==200){//200表示请求一切正常
                String json= EntityUtils.toString(httpResponse.getEntity(),"UTF-8");//获取响应结果的实体对象
                userList =  ObjectMapperUtil.toObject(json,userList.getClass());
            }
        }catch (IOException e){
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        return userList;
    }
}
